package com.lz.autotest.common.utils;

import com.lz.autotest.common.utils.poi.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xddf.usermodel.PresetColor;
import org.apache.poi.xddf.usermodel.XDDFColor;
import org.apache.poi.xddf.usermodel.XDDFSolidFillProperties;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTDLbls;
import org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos;

import java.util.Arrays;
import java.util.List;

/**
 * @author: X
 * @date: Created in 2023/7/5 16:15
 * @Description: 构建excel的每一行
 */
public class ReportExcelUtils {

    public static void builderExcelRow(Sheet sheet, Integer row, List<CellDetail> list) {
        Row target = sheet.createRow(row);
        for (CellDetail cellDetail : list) {
            Cell cell = target.createCell(cellDetail.getColumn());
            cell.setCellValue(cellDetail.getCellValue());
            sheet.setColumnWidth(cellDetail.getColumn(), (int) ((16 + 0.72) * 256));
            cell.setCellStyle(cellDetail.getCellStyle());
        }
    }

    private static XSSFChart createDrawingPatriarch(XSSFSheet sheet, ChartPosition chartPosition, String chartTitle) {
        //创建一个画布
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        //前偏移量四个默认0
        XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, chartPosition.getCol1(), chartPosition.getRow1(), chartPosition.getCol2(), chartPosition.getRow2());
        //创建一个chart对象
        XSSFChart chart = drawing.createChart(anchor);
        //标题
        chart.setTitleText(chartTitle);
        //标题是否覆盖图表
        chart.setTitleOverlay(false);
        return chart;
    }

    /**
     * 创建饼图
     *
     * @param sheet 图表
     * @see PieChart  饼图数据的封装
     * @see ChartPosition 饼图的坐标位置
     */
    public static void createPie(XSSFSheet sheet, ChartPosition chartPosition, PieChart pieChart) {
        String titleName = pieChart.getTitleName();
        List<String> titleList = pieChart.getTitleList();
        List<Double> dataList = pieChart.getDataList();
        XSSFChart chart = createDrawingPatriarch(sheet, chartPosition, titleName);
        //图例位置
        XDDFChartLegend legend = chart.getOrAddLegend();
        legend.setPosition(LegendPosition.LEFT);

        //CellRangeAddress(起始行号，终止行号， 起始列号，终止列号）
        //分类轴标数据，
        XDDFDataSource<String> countries = XDDFDataSourcesFactory.fromArray(titleList.toArray(new String[]{}));
        XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromArray(dataList.toArray(new Double[]{}));
        XDDFChartData data = chart.createData(ChartTypes.PIE, null, null);
        //设置为可变颜色
        data.setVaryColors(true);
        //图表加载数据
        data.addSeries(countries, values);

        //绘制
        chart.plot(data);
        CTDLbls ctdLbls = chart.getCTChart().getPlotArea().getPieChartArray(0).getSerArray(0).addNewDLbls();
        ctdLbls.addNewShowVal().setVal(false);
        ctdLbls.addNewShowLegendKey().setVal(false);
        //类别名称
        ctdLbls.addNewShowCatName().setVal(true);
        //百分比
        ctdLbls.addNewShowSerName().setVal(false);
        ctdLbls.addNewShowPercent().setVal(true);
        //引导线
        ctdLbls.addNewShowLeaderLines().setVal(true);
        //分隔符为分行符
        ctdLbls.setSeparator("\n");
        //数据标签内
        ctdLbls.addNewDLblPos().setVal(STDLblPos.Enum.forString("inEnd"));
    }

    /**
     * 创建折线图
     *
     * @param sheet 图表
     * @see PieChart  饼图数据的封装
     * @see ChartPosition 饼图的坐标位置
     */
    public static void createLine(XSSFSheet sheet, ChartPosition chartPosition, LineChart lineChart) {
        List<String> xAxisList = lineChart.getXAxisList();
        List<String> chartTitleList = lineChart.getTitleList();
        List<List<Double>> chartDataList = lineChart.getDataList();
        String chartTitle = lineChart.getChartTitle();
        XSSFChart chart = createDrawingPatriarch(sheet, chartPosition, chartTitle);
        //图例位置
        XDDFChartLegend legend = chart.getOrAddLegend();
        legend.setPosition(LegendPosition.TOP);
        //分类轴标(X轴),标题位置
        XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
        bottomAxis.setTitle(lineChart.getAxisTitleList().get(1));
        int interval = xAxisList.size() / 10;
        bottomAxis.setMajorUnit(interval);
        bottomAxis.setMinorUnit(interval);
        //值(Y轴)轴,标题位置
        XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
        leftAxis.setTitle(lineChart.getAxisTitleList().get(0));
        //LINE：折线图，
        XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
        XDDFCategoryDataSource countries = XDDFDataSourcesFactory.fromArray(Arrays.copyOf(xAxisList.toArray(), xAxisList.toArray().length, String[].class));
        for (int i = 0; i < chartDataList.size(); i++) {
            List<Double> floats = chartDataList.get(i);
            XDDFNumericalDataSource<Double> dataSource = XDDFDataSourcesFactory.fromArray(floats.toArray(new Double[]{}));
            //图表加载数据，折线
            XDDFLineChartData.Series series = (XDDFLineChartData.Series) data.addSeries(countries, dataSource);
            series.setTitle(chartTitleList.get(i), null);
            //直线
            series.setSmooth(true);
            //设置标记大小
            series.setMarkerSize((short) 2);
        }
        //绘制
        chart.plot(data);
        if (chartDataList.size() == 1) {
            chart.getCTChart().getPlotArea().getLineChartArray(0).addNewVaryColors().setVal(false);
        }
    }

    /**
     * 根据列名获取列值(例如getColumnIndexByAddress("A"),返回1代表第一列),具体打开可以看到excel字母
     */
    public static int getColumnIndexByAddress(String columnAddress) {
        int colNum = 0;
        for (int i = 0; i < columnAddress.length(); i++) {
            char ch = columnAddress.charAt(columnAddress.length() - 1 - i);
            colNum += (ch - 'A' + 1) * Math.pow(26, i);
        }
        return colNum - 1;
    }

    /**
     * 绘制柱状图工具类
     */
    public static void createHistogram(XSSFSheet sheet, HistogramChart histogramChart) {
        // 创建一个画布
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        // 前四个默认0，[0,5]：从0列5行开始;[7,26]:到7列26行结束
        XSSFClientAnchor anchor = drawing.createAnchor(histogramChart.getPosition()[0], histogramChart.getPosition()[1], histogramChart.getPosition()[2], histogramChart.getPosition()[3], histogramChart.getPosition()[4], histogramChart.getPosition()[5], histogramChart.getPosition()[6], histogramChart.getPosition()[7]);
        // 创建一个chart对象
        XSSFChart chart = drawing.createChart(anchor);
        // 标题
        chart.setTitleText(histogramChart.getChartTitle().get(0));
        // 标题覆盖
        chart.setTitleOverlay(false);

        // 图例位置
        XDDFChartLegend legend = chart.getOrAddLegend();
        legend.setPosition(LegendPosition.TOP);

        // 分类轴标(X轴),标题位置
        XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
        bottomAxis.setTitle(histogramChart.getChartTitle().get(1));
        // 值(Y轴)轴,标题位置
        XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
        leftAxis.setTitle(histogramChart.getChartTitle().get(2));

        XDDFCategoryDataSource countries = XDDFDataSourcesFactory.fromArray(histogramChart.getXAxisList());
        XDDFNumericalDataSource<Double> area = XDDFDataSourcesFactory.fromArray(histogramChart.getDataList());

        // bar：条形图，
        XDDFBarChartData bar = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);

        leftAxis.setCrossBetween(AxisCrossBetween.BETWEEN);
        // 设置为可变颜色
        bar.setVaryColors(false);// 如果需要设置成自己想要的颜色，这里可变颜色要设置成false
        // 条形图方向，纵向/横向：纵向
        bar.setBarDirection(BarDirection.COL);

        // 图表加载数据，条形图1
        XDDFBarChartData.Series series1 = (XDDFBarChartData.Series) bar.addSeries(countries, area);
        // 条形图例标题
        series1.setTitle(histogramChart.getChartTitle().get(3), null);
        XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(PresetColor.BLUE_VIOLET));
        // 条形图，填充颜色
        series1.setFillProperties(fill);

        // 绘制
        chart.plot(bar);
    }
}
